package com.example.smartcity.ui.home.fragment

import android.os.Bundle
import android.text.Html
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity.R
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.FragmentFragment1Binding
import com.example.smartcity.databinding.FragmentFragment5Binding
import com.example.smartcity.ui.home.adapter.NewSHotRecyclerViewAdapter
import com.example.smartcity.ui.home.model.NewSRecyclerViewEntity
import com.example.smartcity.ui.newS.NewsViewModel

class fragment5 : Fragment() {
    private val newSViewModel by lazy {
        ViewModelProvider(this)[NewsViewModel::class.java]
    }

    private lateinit var mBinding: FragmentFragment5Binding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentFragment5Binding.inflate(inflater, container, false)

        // 设置新闻列表
        NewSData()

        return mBinding.root
    }
    /**
     * 获取新闻列表
     */
    fun NewSData(){
        // 存储数据
        val listData = ArrayList<NewSRecyclerViewEntity>()


        // 设置RecyclerView适配器
        val layout = LinearLayoutManager(context)
        mBinding.HomeRecyclerView.layoutManager = layout
        val adapter = NewSHotRecyclerViewAdapter(listData)
        mBinding.HomeRecyclerView.adapter = adapter


        // 添加数据
        newSViewModel.newS(21)
        newSViewModel.newSLiveData.observe(this, Observer { resources ->
            val body =  resources.getOrNull()
            if(body != null){
                // 清空数据
                newSViewModel.newSList.clear()
                // 添加数据
                newSViewModel.newSList.addAll(body)
            }

            // 设置数据
            for(i in newSViewModel.newSList){
                val size = newSViewModel.newSList.size
                if(listData.size < size){
                    listData.add(NewSRecyclerViewEntity(
                        SmartCityApplication.url + i.cover,
                        i.title,
                        Html.fromHtml(i.content).toString(),
                        i.commentNum.toString() + "评论",
                        i.publishDate))
                    adapter.notifyItemChanged(listData.size)
                } else break
            }
        })
    }

}